package com.yf.exam.modules.tmpl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.exam.modules.paper.dto.ext.PaperQuDetailDTO;
import com.yf.exam.modules.tmpl.dto.ext.TmplQuDetailDTO;
import com.yf.exam.modules.tmpl.entity.TmplGroup;
import com.yf.exam.modules.tmpl.entity.TmplGroupRule;
import com.yf.exam.modules.tmpl.entity.TmplQu;
import com.yf.exam.modules.tmpl.mapper.TmplQuMapper;
import com.yf.exam.modules.tmpl.service.TmplQuAnswerService;
import com.yf.exam.modules.tmpl.service.TmplQuService;
import com.yf.repo.enums.QuType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
* <p>
* 试卷题目业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2021-04-25 13:59
*/
@Service
public class TmplQuServiceImpl extends ServiceImpl<TmplQuMapper, TmplQu> implements TmplQuService {

    @Autowired
    private TmplQuAnswerService tmplQuAnswerService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAll(String tmplId, Boolean pathScore, String groupId, List<TmplQuDetailDTO> quList) {

        // 当前存在的ID
        List<String> ids = this.findIds(groupId);

        // 保存全部
        this.saveAll(tmplId, ids, pathScore, groupId, quList, false, null);

        // 移除删掉的内容
        if(!CollectionUtils.isEmpty(ids)){
            this.delete(ids);
        }
    }

    /**
     * 保存全部试卷题目
     * @param tmplId
     * @param pathScore
     * @param groupId
     * @param quList
     * @param sub
     */
    public void saveAll(String tmplId, List<String> ids, Boolean pathScore, String groupId, List<TmplQuDetailDTO> quList, boolean sub, String refId) {


        // 题目列表
        if(!CollectionUtils.isEmpty(quList)) {

            int i = 1;
            for (TmplQuDetailDTO item : quList) {

                // 保存基本信息
                TmplQu qu = new TmplQu();
                if(StringUtils.isBlank(item.getId())){
                    qu.setId(IdWorker.getIdStr());
                }else {
                    qu.setId(item.getId());
                }
                qu.setQuType(item.getQuType());
                qu.setScore(item.getScore());
                qu.setQuId(item.getQuId());
                qu.setGroupId(groupId);
                qu.setTmplId(tmplId);
                qu.setSort(i);

                // 是子项目
                if(sub){
                    qu.setChild(true);
                    qu.setRefId(refId);
                }
                // 修改或添加
                this.saveOrUpdate(qu);

                i++;
                tmplQuAnswerService.saveAll(qu.getId(), qu.getQuType(), qu.getScore(), pathScore, item.getContent(), item.getAnswerList());

                // 保存组合题子项
                if(QuType.MIX.equals(qu.getQuType())){
                    List<TmplQuDetailDTO> subList = item.getSubList();
                    this.saveAll(tmplId, ids, pathScore, groupId, subList, true, qu.getId());
                }

                // 排除已添加的，不被删除
                ids.remove(qu.getId());
            }
        }
    }


    /**
     * 查找已存在列表
     * @param groupId
     * @return
     */
    private List<String> findIds(String groupId){
        QueryWrapper<TmplQu> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(TmplQu::getId)
                .eq(TmplQu::getGroupId, groupId);
        List<TmplQu> list = this.list(wrapper);
        List<String> ids = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            for (TmplQu item: list){
                ids.add(item.getId());
            }
        }
        return ids;
    }

    @Override
    public void removeByGroups(List<String> groupIds) {
        QueryWrapper<TmplQu> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(TmplQu::getTmplId)
                .in(TmplQu::getGroupId, groupIds);

        List<TmplQu> list = this.list(wrapper);
        List<String> ids = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            for (TmplQu item: list){
                ids.add(item.getId());
            }
        }

        if(!CollectionUtils.isEmpty(ids)){
            this.delete(ids);
        }
    }

    @Override
    public List<PaperQuDetailDTO> listForCreate12(TmplGroup group) {
        return baseMapper.findForCreate(group.getId(), group.getQuRand(), group.getItemRand());
    }

    @Override
    public List<PaperQuDetailDTO> listForCreate3(List<String> excludes, TmplGroup group, TmplGroupRule rule) {
        return baseMapper.listWithRule(excludes,
                rule.getRepoId(),
                rule.getChapterId(),
                rule.getLevel(),
                rule.getQuType(),
                rule.getNum(),
                group.getQuRand(),
                group.getItemRand()
        );
    }

    /**
     * 根据ID删除
     * @param ids
     */
    private void delete(List<String> ids) {
        QueryWrapper<TmplQu> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(TmplQu::getId, ids);
        this.remove(wrapper);

        // 删除答案
        tmplQuAnswerService.removeByRefIds(ids);
    }
}
